<template>
  <el-dialog title="选择用户" :visible.sync="dialogVisible" width="90%">
    <div class="app-container">
      <el-row :gutter="10">
        <el-col :span="15">
          <!--用户数据-->
          <el-form
            v-show="showSearch"
            ref="queryForm"
            :inline="true"
            :model="queryParams"
            label-width="68px"
          >
            <el-row>
              <el-col :span="9">
                <el-form-item label="用户名称" prop="userName">
                  <el-input
                    v-model="queryParams.userName"
                    clearable
                    placeholder="请输入用户名称"
                    size="small"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="手机号码" prop="phonenumber">
                  <el-input
                    v-model="queryParams.phonenumber"
                    clearable
                    placeholder="请输入手机号码"
                    size="small"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-button
                    icon="el-icon-search"
                    size="mini"
                    type="primary"
                    @click="handleQuery"
                  >
                    搜索
                  </el-button>
                  <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                  >
                    重置
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-table
            ref="userTable"
            v-loading="loading"
            :data="userList"
            row-key="id"
            @select="handleSelectionChange"
            @select-all="handleSelectionChange"
          >
            <el-table-column
              v-if="multiple"
              align="center"
              type="selection"
              width="50"
              :reserve-selection="true"
            />
            <el-table-column v-else label width="45">
              <template slot-scope="scope">
                <el-radio v-model="radioId" :label="scope.row.id" @change="handleSingleUser(scope.row)">
                  &nbsp;
                </el-radio>
              </template>
            </el-table-column>
            <el-table-column
              key="userId"
              align="center"
              label="用户编号"
              prop="id"
            />
            <el-table-column
              key="userName"
              :show-overflow-tooltip="true"
              align="center"
              label="用户名称"
              prop="userName"
            />
            <el-table-column
              key="nickName"
              :show-overflow-tooltip="true"
              align="center"
              label="用户昵称"
              prop="nickName"
            />
            <el-table-column
              key="deptName"
              :show-overflow-tooltip="true"
              align="center"
              label="部门"
              prop="dept.deptName"
            />
            <el-table-column
              key="phonenumber"
              align="center"
              label="手机号码"
              prop="phonenumber"
              width="120"
            />
            <el-table-column
              align="center"
              label="创建时间"
              prop="createTime"
              width="160"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :limit.sync="queryParams.size"
            :page.sync="queryParams.current"
            :total="total"
            @pagination="getList"
          />
        </el-col>
        <el-col :span="9">
          <p class="title-text pl5">
            已选择用户列表
          </p>
          <el-table border :data="selectedUserList" max-height="500">
            <el-empty slot="empty" description="暂无选择用户" />
            <el-table-column
              key="userId"
              align="center"
              label="用户编号"
              prop="id"
            />
            <el-table-column
              key="userName"
              :show-overflow-tooltip="true"
              align="center"
              label="用户名称"
              prop="userName"
            />
            <el-table-column
              key="nickName"
              :show-overflow-tooltip="true"
              align="center"
              label="用户昵称"
              prop="nickName"
            />
            <el-table-column
              align="center"
              class-name="small-padding fixed-width"
              label="操作"
              width="160"
            >
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  type="text"
                  @click="deleteSelectedUserHandle(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitSelectedUserHandle">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {pageUser} from "@/api/system/user"
import _ from "lodash"

export default {
  name: "UserChooseTable",
  props: {
    // 多选
    multiple: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      radioId: null,
      // 遮罩层
      loading: true,
      // 弹窗是否显示
      dialogVisible: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 选中的用户
      selectedUserList: [],
      // 记录默认选中的行Id
      defaultSelectRows: [],
      // 记录被删除的行id 避免分页导致选中状态未被取消
      removedSelectRows: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 5,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 显示用户选择弹窗
    showDialog(userList) {
      this.dialogVisible = true
      // 比较删除掉的
      this.removedSelectRows = _.difference(
        this.selectedUserList,
        userList
      ).map((item) => item.id)
      console.log(_.difference(this.selectedUserList, userList))
      this.selectedUserList = userList
      // 默认选中
      this.defaultSelectRows = userList.map((item) => item.id)
      this.$nextTick(() => {
        this.handleDefaultRowSelection()
      })
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      pageUser(this.queryParams).then((response) => {
        this.userList = response.data.records
        this.total = response.data.total
        this.loading = false
        this.handleDefaultRowSelection()
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.selectedUserList = _.uniqBy(selection, "id")
    },
    deleteSelectedUserHandle(row) {
      let index = _.findIndex(this.selectedUserList, ["id", row.id])
      this.selectedUserList.splice(index, 1)
      let user = this.userList.find((item) => item.id == row.id)
      this.$refs.userTable.toggleRowSelection(user, false)
      // 记录 避免不在同一页导致删除失败
      this.removedSelectRows.push(row.id)
    },
    handleDefaultRowSelection() {
      // 比较对象 toggleRowSelection 不是同一个对象不生效。。。
      if (
        this.defaultSelectRows.length == 0 &&
        this.removedSelectRows.length == 0
      ) {
        return
      }
      this.userList.forEach((user) => {
        // 设置选中
        let index = this.defaultSelectRows.findIndex((item) => user.id == item)
        if (index !== -1) {
          this.$refs.userTable.toggleRowSelection(user, true)
          this.defaultSelectRows.splice(index, 1)
        }
        // 取消选中
        let index1 = this.removedSelectRows.findIndex((item) => user.id == item)
        if (index1 !== -1) {
          this.$nextTick(() => {
            this.$refs.userTable.toggleRowSelection(user, false)
          })
          this.removedSelectRows.splice(index, 1)
        }
      })
    },
    handleSingleUser(user) {
      this.selectedUserList = [user]
    },
    submitSelectedUserHandle() {
      this.dialogVisible = false
      this.$emit("submit", this.selectedUserList)
    }
  }
}
</script>
